import sqlite3
from entity.User import *


class User_mapper:
    def __init__(self,db_path):  # 构造方法
        self.conn = sqlite3.connect(db_path)

    def __del__(self):  # 销毁勾子
        self.conn.cursor()

    def get_all_user_data(self) -> list:
        cursor = self.conn.cursor()
        cursor.execute('select * from user')
        return cursor.fetchall()

    def get_user_by_name(self, name) -> User:
        cursor = self.conn.cursor()
        cursor.execute('select * from user where name=?', (name,))
        value = cursor.fetchall()[0]  # 这里name是唯一键
        user = None
        if len(value) > 0:
            user = User(value[0], value[1], value[2], value[3])
        return user

    # 通常用在判断新用户首次登录
    def find_user_name(self, user_name: str) -> bool:
        cursor = self.conn.cursor()
        cursor.execute('select * from user where name=?', (user_name,))
        value = cursor.fetchall()
        return len(value) > 0

    def login_game(self, user_name: str) -> int:  # 玩家登录游戏
        cursor = self.conn.cursor()
        if self.find_user_name(user_name):
            cursor.execute('SELECT score from score where user_name=? ORDER BY score DESC LIMIT 1', (user_name,))
            result = cursor.fetchall()
            if len(result) > 0:
                return result[0][0]
            return 0
        else:  # 新用户
            timestamp = int(time.time())
            cursor.execute('INSERT INTO user (name,create_time) VALUES (?,?)', (user_name, timestamp))
            self.conn.commit()
            return 0


if __name__ == '__main__':
    user_mapper = User_mapper("../db/data.db")
    result_user = user_mapper.login_game('canyue')
    print(result_user)
